import aaf
import os

from optparse import OptionParser

from aaf.component import Filler
from aaf.component import Sequence
from aaf.component import SourceClip
from aaf.component import Timecode
from aaf.essence import CDCIDescriptor
from aaf.essence import Locator
from aaf.essence import NetworkLocator
from aaf.mob import CompositionMob
from aaf.mob import MasterMob
from aaf.mob import SourceMob
from aaf.mob import TimelineMobSlot
from aaf.util import SourceRef


def walk_properties(space, iter_item):
    parser = OptionParser()
    parser.add_option('--show_dictionary', action='store_true', default=False, dest='show_dict',
                      help="show dictionary properties")
    parser.add_option('--show_stream', action='store_true', default=False, dest='show_stream',
                      help="show binary stream data")
    (options, args) = parser.parse_args()

    for item in iter_item:
        value = item
        if isinstance(item, aaf.property.PropertyItem):
            value = item.value
        name = ""

        if hasattr(item, 'name'):
            name = item.name or ""

        print(space, name, value)

        if isinstance(value, aaf.dictionary.Dictionary) and not options.show_dict:
            continue
        # don't dump out stream data, its ugly
        if isinstance(value, aaf.iterator.TypeDefStreamDataIter) and not options.show_stream:
            continue

        s = space + '   '
        if isinstance(value, aaf.base.AAFObject):
            walk_properties(s, value.properties())
        if isinstance(value, aaf.iterator.BaseIterator):
            walk_properties(s, value)
        pass

output_aaf = 'resources/aaf_build.aaf'
if os.path.exists(output_aaf):
    os.remove(output_aaf)
aaf_file = aaf.open(output_aaf, 'rw')
print "[aaf_file]:" + str(aaf_file)
print

class_iid = aaf_file.class_iid
header = aaf_file.header
storage = aaf_file.storage
dictionary = aaf_file.dictionary

print "[aaf_file.class_iid]:" + str(class_iid)
print "[aaf_file.header]:" + str(header)
print "[aaf_file.storage]:" + str(storage)
print "[aaf_file.dictionary]:" + str(dictionary)
print

# # New TimelineMobSlot
# timelineMobSlot = TimelineMobSlot(aaf_file)

# __init__(self, root, media_kind = None, lib.aafLength_t length = 0, SourceRef source_ref = None):
# sourceRef = SourceRef()
# sourceClip = SourceClip(aaf_file,media_kind="picture",length=100)

# MasterMob
masterMob = MasterMob(aaf_file, "MasterMob Build")
aaf_file.storage.add_mob(masterMob)

file_path = "D:/ZhanPeng/Source/test.mov"
file_path = "file:///D:/ZhanPeng/Source/A175_C01_09_s1_pengjiao_v005_2_Check/Left/L_A175_C016_1225V9_001.00097064.dpx"
locator = NetworkLocator(aaf_file,path=file_path)
# locator = NetworkLocator(aaf_file,path="file:///D:/ZhanPeng/Source/A175_C01_09_s1_pengjiao_v005_2_Check/Left/L_A175_C016_1225V9_001.00097064.dpx")
## ERROR: create_essence will make the tif file is 4kb
# masterMob.create_essence(slot_index=0, media_kind="picture", codec_name="JPEG", edit_rate=24, sample_rate=24, compress=True, locator=locator)
# masterMob.import_video_essence(path = file_path, frame_rate = 24)

frame_name = "V1-0001_IMG_3713.00000006.tif"
temp_path = "temp/" + frame_name

temp_locator = NetworkLocator(aaf_file,path=temp_path)
essenceAccess = masterMob.create_essence(slot_index=0, media_kind="picture", codec_name="JPEG", edit_rate=24, sample_rate=24, compress=True, locator=None)


# find sourcemob.EssenceDescription.Locator.URLString
for aaf_mob in storage.mobs():
    if "SourceMob" in str(type(aaf_mob)):
        sourceMob = aaf_mob
        esscence_descriptor = sourceMob.essence_descriptor
        print sourceMob
        if "CDCIDescriptor" in str(type(esscence_descriptor)):
            cdciDescriptor = esscence_descriptor
            local_locator = NetworkLocator(aaf_file,path="file:///D:/ZhanPeng/Source/tiff/" + frame_name)
            cdciDescriptor.append_locator(local_locator)


for slot in masterMob.slots():
    print str(slot) + " | " + str(slot.slotID)
master_clip = masterMob.create_clip(slot.slotID, length=20, start_time=6)

# print str(type(master_clip))
# SourceMob
# sourceMob = SourceMob(aaf_file,"SourceMob Build")
# cdciDescriptor = CDCIDescriptor(aaf_file)
# locator = NetworkLocator(aaf_file,path="file:///D:/ZhanPeng/Source/IMG_3713.mov")
# cdciDescriptor.append_locator(locator)
# # cdciDescriptor.length = 307
# sourceMob.essence_descriptor = cdciDescriptor
# sourceMob.length = 307

# aaf_file.storage.add_mob(sourceMob)

# New method to create clip
# sourceClip = SourceClip(aaf_file,media_kind="picture", length=100)
# sourceClip.mob_id = sourceMob.umid
# sourceClip.length = 307
# slot_id = None
# for slot in sourceMob.slots():
#     print str(slot) + " | " + str(slot.slotID)
#     # slot_id = slot.slotID
# sourceClip = sourceMob.create_clip(length = 10, start_time = 0)

# New CompositionMob
compositionMob = CompositionMob(aaf_file,'Timeline Build')
edit_rate = 24

# hrieo soft show use Primary timecode not found in AAF file
# __init__(self, root, lib.aafLength_t length, lib.aafFrameOffset_t start_frame,lib.aafUInt16 fps, drop = False):
timecode = Timecode(aaf_file, length=1000, start_frame=0, fps=24, drop=False)
compositionMob.append_new_timeline_slot(edit_rate, timecode, slotID=0, slot_name='TrackTimecode Build', origin=0)

# __init__(self, root, media_kind not None, lib.aafLength_t length):
filler = Filler(aaf_file, media_kind="picture", length=24)
sequence = Sequence(aaf_file, media_kind="picture")
sequence.append(filler)
# sequence.append(sourceClip)
# sequence.length = 307 + 100
sequence.append(master_clip)
filler_2 = Filler(aaf_file, media_kind="picture", length=24)
sequence.append(filler_2)
segment = sequence
compositionMob.append_new_timeline_slot(edit_rate, segment, slotID=0, slot_name='Track Build', origin=0)


# Add CompositionMob
aaf_file.storage.add_mob(compositionMob)
aaf_file.save()

walk_properties("", aaf_file.header.properties())

aaf_file.close()

aaf_file = aaf.open(output_aaf, 'r')
print "[aaf_file.header.properties]:"
# walk_properties("", aaf_file.header.properties())
print "[aaf_file.storage.properties]:"
walk_properties("", aaf_file.storage.properties())
aaf_file.close()
